26. 练习:字典和恒等运算符
练习:定义字典
请定义一个叫做 population
的字典,其中包含以下数据:
键 | 值 |
---|---|
Shanghai | 17.8 |
Istanbul | 13.3 |
Karachi | 13.0 |
Mumbai | 12.5 |
Start Quiz:
# Define a Dictionary, population,
# that provides information
# on the world's largest cities.
# The key is the name of a city
# (a string), and the associated
# value is its population in
# millions of people.
# Key | Value
# Shanghai | 17.8
# Istanbul | 13.3
# Karachi | 13.0
# Mumbai | 12.5
不可变键
SOLUTION:
- `str`
- `int`
- `float`
练习:查看哪些值不在字典里
SOLUTION:
发生 `KeyError`返回默认值的 get
字典有一个也很有用的相关方法,叫做 get
。get 会在字典中查询值,但是和方括号不同,如果没有找到键,get 会返回 None(或者你所选的默认值)。如果你预计查询有时候会失败,get
可能比普通的方括号查询更合适。
>>> elements.get('dilithium')
None
>>> elements['dilithium']
KeyError: 'dilithium'
>>> elements.get('kryptonite', 'There\'s no such element!')
"There's no such element!"
在上个示例中,我们指定了一个默认值(字符串 'There\'s no such element!
),当键没找到时,get 会返回该值。
检查是否相等与恒等:==
与 is
检查是否相等与恒等
SOLUTION:
True, True, True, FalseStart Quiz:
# Test the code here if you'd like
a = [1, 2, 3]
b = a
c = [1, 2, 3]